﻿using Infrastructure.Extensions;
using Infrastructure.Helper;
using Infrastructure.Model.ApiResult;
using Infrastructure.Model.UserAuth;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Caching.Distributed;

namespace Infrastructure.Attribute
{
    /// <summary>
    /// 授权过滤器，在控制器操作之前进行身份验证和授权检查。
    /// 实现了 IAuthorizationFilter 接口，并提供身份验证和授权的逻辑。
    /// </summary>
    public class VerifyAttribute : System.Attribute, IAuthorizationFilter, IFilterMetadata
    {
        private readonly IDistributedCache _distributedCache;

        // 分布式缓存依赖，
        public VerifyAttribute(IDistributedCache distributedCache)
        {
            _distributedCache = distributedCache;
        }
       
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            // 检查是否允许匿名访问
            bool isAnonymous = context.ActionDescriptor is ControllerActionDescriptor descriptor &&
                              descriptor.MethodInfo.GetCustomAttributes(inherit: true)
                                  .Any(a => a.GetType() == typeof(AllowAnonymousAttribute));
            
            if (!isAnonymous)
            {
                // 获取客户端 IP 和路径（用于日志/审计）
                string clientIp = context.HttpContext.GetClientUserIp();
                string path = context.HttpContext.Request.Path;

                // 直接解析 JWT 获取用户信息
                LoginUser loginUser = JwtUtil.GetLoginUser(context.HttpContext);
                // 修正逻辑：仅当用户无效时拒绝访问
                if (loginUser == null || string.IsNullOrEmpty(loginUser.UserId))
                {
                    string msg = $"请求访问 {path} 失败：未授权或 Token 无效";
                    context.Result = new JsonResult(new ApiResult(401, msg));
                }
            }
        }
      
    }
}
